package com.example.springboot_code_read.genericConverter;

import com.example.springboot_code_read.bean.DateObj;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.util.ReflectionUtils;

import java.util.Date;

public class GenericConverterTest {

    public static void main(String[] args) {

        DefaultConversionService service = new DefaultConversionService();

        service.addConverter(new AnnotatedStringToDateConverter());

        TypeDescriptor descriptor1 = TypeDescriptor.valueOf(String.class);
        TypeDescriptor descriptor2 = new TypeDescriptor(ReflectionUtils.findField(DateObj.class, "date"));

        Date date = (Date) service.convert("2023-01-01", descriptor1, descriptor2);

        // 定义另一组源类型和目标类型，准备将另一个 String 格式转换为 Date
        TypeDescriptor sourceType2 = TypeDescriptor.valueOf(String.class);
        TypeDescriptor targetType2 = new TypeDescriptor(ReflectionUtils.findField(DateObj.class, "dateTime"));
        // 执行转换操作
        Date dateTime = (Date) service.convert("2023-01-01 23:59:59", sourceType2, targetType2);

        DateObj dateObj = new DateObj();
        dateObj.setDate(date);
        dateObj.setDateTime(dateTime);

        System.out.println(dateObj);

    }

}
